package com.jack006.api.interceptors;

import com.jack006.exception.GraceException;
import com.jack006.grace.result.ResponseStatusEnum;
import com.jack006.utils.IpUtils;
import com.jack006.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname PassportInterceptor
 * @Description 用户通行拦截器
 * @Date 2021-06-13 15:28
 * @Created by jack
 */
public class PassportInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisOperator redisOperator;

    public static final String MOBILE_SMSCODE="mobile:smscode";

    /**
     * 拦截请求进入 controller 之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获得用户 IP
        String userIp = IpUtils.getRequestIp(request);

        boolean keyIsExist = redisOperator.keyIsExist(MOBILE_SMSCODE + ":" + userIp);

        /**
         * false: 请求被拦截
         * true： 请求通过验证，放行
         */
        if (keyIsExist) {
            GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
            return false;
        }

        return true;
    }

    /**
     * 在请求访问到 controller,渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在请求访问到 controller,渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
